package cn.xej.demo;

import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Author alicat.xu
 * @Date 2021/10/26 7:53 下午
 */
public class IN implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println(handler);
        if (handler instanceof HandlerMethod){
            HandlerMethod methodHandle = (HandlerMethod)handler;
//            System.out.println(methodHandle);
            //获取方法所有的行参变量
            MethodParameter[] methodParameters = methodHandle.getMethodParameters();
            PutResource annotation1 = methodParameters[0].getParameter().getAnnotation(PutResource.class);
            System.out.println("变量："+annotation1.name());

            //获取方法的类对象  方式一
            Method method = methodHandle.getMethod();
            Class<?> aClass = method.getDeclaringClass();
            PutResource annotation2 = aClass.getAnnotation(PutResource.class);
            System.out.println("类："+annotation2.name());

            //获取方法的类对象  方式二
            Class<?> beanType = methodHandle.getBeanType();
            PutResource annotation = beanType.getAnnotation(PutResource.class);
            System.out.println("类："+annotation.name());

            //获取方法上标注的自定义注解
            PutResource methodAnnotation = methodHandle.getMethodAnnotation(PutResource.class);
            System.out.println("方法："+methodAnnotation.name());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
